package net.molchat.web.spring;


import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import net.molchat.web.UrlUtil;
import net.molchat.web.UserLoginBlock;


/**
 * A set of utilites to process/prepare for rendering user information.
 * 
 * @author Valentyn Markovych
 * 
 */
public class UserUtil {

private String loginUrl;
private String logoutUrl;
private String defaultUserName;
private String backUrlParameterName;


/**
 * @return current parameter name for URL to return from Login page
 */
public String getBackUrlParameterName() {

	return backUrlParameterName;
}


/**
 * @param backUrlParameterName
 */
public void setBackUrlParameterName(String backUrlParameterName) {

	this.backUrlParameterName = backUrlParameterName;
}


/**
 * Create and return User information regarding login/logout links.
 * 
 * @param request
 * @return User information block created.
 */
public UserLoginBlock getUserLoginBlock(HttpServletRequest request) {

	UserLoginBlock ub = new UserLoginBlock();
	ub.setLoginUrl(loginUrl + '?' + backUrlParameterName + '=' + UrlUtil.ReconstructFullUrl(request).toString());
	ub.setLogoutUrl(logoutUrl);

	Principal principal = request.getUserPrincipal();
	if (principal != null) {
		ub.setUserName(principal.getName());
	} else {
		ub.setUserName(defaultUserName);
	}

	return ub;
}


/**
 * @return current loginUrl.
 */
public String getLoginUrl() {

	return loginUrl;
}


/**
 * @param loginUrl
 */
public void setLoginUrl(String loginUrl) {

	this.loginUrl = loginUrl;
}


/**
 * @return current user name, that would be used for UNauthenticated users (e.
 *         g. "Guest" or "Not authenticated");
 */
public String getDefaultUserName() {

	return defaultUserName;
}


/**
 * @param defaultUserName
 */
public void setDefaultUserName(String defaultUserName) {

	this.defaultUserName = defaultUserName;
}


/**
 * @return current logout URL
 */
public String getLogoutUrl() {

	return logoutUrl;
}


/**
 * @param logoutUrl
 */
public void setLogoutUrl(String logoutUrl) {

	this.logoutUrl = logoutUrl;
}

}
